package com.nl.controller.web.service;

import java.util.*;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.druid.sql.ast.statement.SQLIfStatement.Else;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.mapper.CommonMapper;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.CRMOpenInfo;
import com.nl.controller.web.bean.SmsMgrGovernmentInfo;
import com.nl.controller.web.bean.SmsMgrInfo;
import com.nl.controller.web.bean.CRMFindMgr.MgrInfo;
import com.nl.controller.web.mapper.CRMMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CRMInterfaceService {

	@Autowired
	private CommonMapper commonMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private CRMMapper cRMMapper;

	private final String jZZWUrl = "http://10.32.42.77:10121/govSms/callback/smsChannel";// 精准政务开户信息同步

	private final String HYMP = "1";
	private final String YJDX = "2";
	private final String FGDMT = "3";

	public JSONObject selectMgrNameLike(String cRMReqMgrList) {
		
		String resultDesc = "";
		String sendNumber;
		List<MgrInfo> mgrInfoList = new ArrayList<>();
		JSONObject retMap = new JSONObject();
		try {
			if (cRMReqMgrList != null && !"".equals(cRMReqMgrList)) {
				JSONObject jsonObject = JSONObject.parseObject(cRMReqMgrList);
				log.info("【CRM项目信息查询】请求参数：{}", jsonObject.toString());
				String channel = jsonObject.getString("channel");
				log.info("【CRM项目信息查询】请求渠道：{}", channel);
				String key = jsonObject.getString("mgrName");
				log.info("【CRM项目信息查询】项目名称联想：{}", key);
				String streamSeq = jsonObject.getString("streamSeq");
				log.info("【CRM项目信息查询】流水号：{}", streamSeq);
				String busiType = jsonObject.getString("busiType");
				if (key != null && key.length() > 0) {
					List<SmsMgrInfo> list;
					List<SmsMgrGovernmentInfo> listG;
					List<SmsMgrInfo> listY;

					if (HYMP.equals(busiType) || YJDX.equals(busiType)) {
						list = commonService.selectMgrNameLike(key, "", "");// 欢迎短信
						// listG = commonService.selectMgrNameLikeG(key);//精准政务
						// listY= commonService.selectMgrNameLikeY(key);//应急短信
						for (SmsMgrInfo smsMgrInfo : list) {
							if ("11".equals(smsMgrInfo.getCityId())) {
								sendNumber = "106571103" + smsMgrInfo.getCityExtId();
							} else {
								sendNumber = "106571102" + smsMgrInfo.getCityExtId();
							}
							String mgrName = smsMgrInfo.getName();
							MgrInfo mgrInfo = new MgrInfo();
							String openAccount = smsMgrInfo.getOpenAccount();
							// 未开户
							if ("-1".equals(openAccount)) {
								openAccount = "0";
							} else if ("0".equals(openAccount)) {
								// 已销户
								openAccount = "-1";
							}

							mgrInfo.setOpenAccout(openAccount);
							mgrInfo.setSendNumber(sendNumber);
							mgrInfo.setMgrName(mgrName + "(欢迎名片)");

							mgrInfoList.add(mgrInfo);
						}
						// for (SmsMgrGovernmentInfo smsMgrGovernmentInfo :
						// listG) {
						// String mgrNameG = smsMgrGovernmentInfo.getMgrName();
						// String sendNumberG =
						// smsMgrGovernmentInfo.getSendNumber();
						// MgrInfo mgrInfo = new MgrInfo();
						// mgrInfo.setSendNumber(sendNumberG);
						// mgrInfo.setMgrName(mgrNameG+"标签名片");
						// mgrInfoList.add(mgrInfo);
						// }
						// for (SmsMgrInfo smsMgrInfo : listY) {
						// sendNumber="106571606"+smsMgrInfo.getCityExtId();
						// String mgrName = smsMgrInfo.getName();
						// MgrInfo mgrInfo = new MgrInfo();
						// mgrInfo.setSendNumber(sendNumber);
						// mgrInfo.setMgrName(mgrName+"(应急名片)");
						// mgrInfoList.add(mgrInfo);
						// }
					} else if (FGDMT.equals(busiType)) {
						list = commonService.selectSignatureNameLike(key);
						System.out.println("----" + key);
						for (SmsMgrInfo smsMgrInfo : list) {
							MgrInfo mgrInfo = new MgrInfo();
							mgrInfo.setSendNumber(smsMgrInfo.getCityExtId());
							mgrInfo.setMgrName(smsMgrInfo.getName());
							mgrInfo.setOpenAccout(smsMgrInfo.getOpenAccount());
							mgrInfoList.add(mgrInfo);
						}
					}
				}
				if (mgrInfoList == null || mgrInfoList.isEmpty()) {
					if (HYMP.equals(busiType) || YJDX.equals(busiType)) {
						retMap.put("mgrInfo", "未找到项目，请输入正确的项目简称");
					} else if (FGDMT.equals(busiType)) {
						retMap.put("mgrInfo", "未找到签名，请输入正确的签名简称");
					}

				} else {
					retMap.put("mgrInfo", mgrInfoList);
				}
				retMap.put("channel", channel);
				retMap.put("streamSeq", streamSeq);
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultDesc = "CRM项目名称联想接口异常,error:" + e.getMessage();
			e.printStackTrace();
			log.info("调用CRM项目名称联想接口失败");
			retMap.put("resultDesc", resultDesc);
		}
		return retMap;
	}

	// @SystemServiceLog(description = "CRM开户信息同步", value = false)

	public JSONObject addOpenInfo(String cRMOpenInfo) {
		CRMOpenInfo crmOpenInfo = JSON.parseObject(cRMOpenInfo, CRMOpenInfo.class);
		log.info("【CRM开户信息同步】请求参数：{}", crmOpenInfo.toString());
		String resultCode = "-1";
		String resultDesc = "失败";
		int result;
		String sendNumber;
		JSONObject retMap = new JSONObject();
		try {
			String channel = crmOpenInfo.getChannel();
			log.info("【CRM开户信息同步】请求渠道：{}", channel);
			String streamSeq = crmOpenInfo.getStreamSeq();
			log.info("【CRM开户信息同步】流水号：{}", streamSeq);
			sendNumber = crmOpenInfo.getSendNumber();
			log.info("【CRM开户信息同步】短信通道号：{}", sendNumber);
			List<SmsMgrGovernmentInfo> smsMgrGovernmentInfos = commonMapper.qryInfoWithecId(crmOpenInfo.getEcId());
			String ops1 = crmOpenInfo.getOps();
			log.info("【CRM开户信息同步】操作类型：{}", ops1);
			
				String jSendNumber = sendNumber.substring(0, 8);
				String hySendNumber = sendNumber.substring(0, 9);
				String yjSendNumber = sendNumber.substring(0, 13);
				if (("106571102".equals(hySendNumber)) || ("106571103".equals(hySendNumber))) {
					if ("1".equals(ops1)) {
						String cityExtId = sendNumber.substring(9);
						String openAccount = cRMMapper.qryMgrByCityExtId(cityExtId);
						List<String> ecId = cRMMapper.qryEcId(sendNumber, "1");
						if ("1".equals(openAccount) && null != ecId && 0 != ecId.size()) {
							if ("1".equals(channel)) {
								crmOpenInfo.setOpenResult("-1");
								result = cRMMapper.addOpenInfo(crmOpenInfo);
								if (result == 1) {
									resultCode = "-1";
									resultDesc = "失败,该项目已有集团开户.";
								}
								log.info("开户失败，该项目已有集团开户,sendNumber:" + sendNumber);
								retMap.put("channel", channel);
								retMap.put("streamSeq", streamSeq);
								retMap.put("resultCode", resultCode);
								retMap.put("resultDesc", resultDesc);
								return retMap;
							}
						}
					}
				}
				
				//记录crm同步记录
				if ("1".equals(channel)) {

					crmOpenInfo.setOpenResult("0");
					result = cRMMapper.addOpenInfo(crmOpenInfo);
					log.info("【CRM开户信息同步】", result);
					if (result == 1) {
						resultCode = "0";
						resultDesc = "成功";
					}
					retMap.put("channel", channel);
					retMap.put("streamSeq", streamSeq);
				}
				// 欢迎5G多媒体短信
				if ("106571108".equals(hySendNumber)) {
					// 判断欢迎短信开户，开户将字段置为1
					String ops = crmOpenInfo.getOps();
					String ecId = crmOpenInfo.getEcId();
					log.info("【CRM开户信息同步】欢迎5G多媒体短信判断操作类型：{}", ops);
					String signId = cRMMapper.qrySignIdByNumber(sendNumber);
					if ("1".equals(ops)) {
						// 开户
						String cityExtId = sendNumber.substring(9);
						log.info("【CRM开户信息同步】欢迎5G多媒体短信修改开户的地市编码：{}", cityExtId);
						int resultOpen = cRMMapper.open5gAccount(sendNumber);
						//同时变更使用该签名的项目开户状态
						resultOpen = cRMMapper.update5gMgrOpenAccount(signId, "1");
						
						log.info("【CRM开户信息同步】欢迎5G多媒体短信修改开户：{}", resultOpen == 1 ? "成功" : "失败");
					} else if ("3".equals(ops)) {
						// 销户
						String cityExtId = sendNumber.substring(9);
						log.info("【CRM开户信息同步】欢迎5G多媒体短信修改开户的地市编码：{}", cityExtId);
						int resultOpen = cRMMapper.update5gAccount(sendNumber);
						//同时变更使用该签名的项目开户状态
						resultOpen = cRMMapper.update5gMgrOpenAccount(signId, "0");
						log.info("【CRM开户信息同步】欢迎5G多媒体短信修改开户：{}", resultOpen == 1 ? "成功" : "失败");

					}if ("4".equals(ops)) {
						// 集团欠费
						cRMMapper.set5gIsArrearage(sendNumber, "1");
						cRMMapper.update5gMgrIsArrearage(signId, "1");
						resultCode = "0";
						resultDesc = "成功";
						retMap.put("channel", channel);
						retMap.put("streamSeq", streamSeq);

					} else if ("5".equals(ops)) {
						//集团恢复
						cRMMapper.set5gIsArrearage(sendNumber, "0");
						cRMMapper.update5gMgrIsArrearage(signId, "0");
						resultCode = "0";
						resultDesc = "成功";
						retMap.put("channel", channel);
						retMap.put("streamSeq", streamSeq);
					}

					// 匹配精准政务
				} else if ("10657016".equals(jSendNumber)) {
					if ("1".equals(ops1)) {
						commonMapper.updateJzzwecId(crmOpenInfo.getEcId(), sendNumber);
					}
					JZZW(cRMOpenInfo);
					// 匹配欢迎短信
				} else if (("106571102".equals(hySendNumber)) || ("106571103".equals(hySendNumber))) {
					// 判断欢迎短信开户，开户将字段置为1
					String ops = crmOpenInfo.getOps();
					String ecId = crmOpenInfo.getEcId();
					log.info("【CRM开户信息同步】欢迎短信判断操作类型：{}", ops);
					if ("1".equals(ops)) {
						// 开户
						String cityExtId = sendNumber.substring(9);
						log.info("【CRM开户信息同步】欢迎短信修改开户的地市编码：{}", cityExtId);
						int resultOpen = cRMMapper.openAccount(ecId, cityExtId);
						log.info("【CRM开户信息同步】欢迎短信修改开户：{}", resultOpen == 1 ? "成功" : "失败");
					} else if ("3".equals(ops)) {
						// 销户
						String cityExtId = sendNumber.substring(9);
						log.info("【CRM开户信息同步】欢迎短信修改开户的地市编码：{}", cityExtId);
						int resultOpen = cRMMapper.updataAccount(cityExtId);
						log.info("【CRM开户信息同步】欢迎短信修改开户：{}", resultOpen == 1 ? "成功" : "失败");

					}else if ("4".equals(ops1)) {
						// 集团欠费
						if (!Objects.isNull(smsMgrGovernmentInfos)) {
							JZZW(cRMOpenInfo);
						}
						cRMMapper.setIsArrearage(crmOpenInfo.getEcId(), "1");
						resultCode = "0";
						resultDesc = "成功";
						retMap.put("channel", channel);
						retMap.put("streamSeq", streamSeq);

					} else if ("5".equals(ops1)) {
						// 集团未欠费
						if (!Objects.isNull(smsMgrGovernmentInfos)) {
							JZZW(cRMOpenInfo);
						}
						cRMMapper.setIsArrearage(crmOpenInfo.getEcId(), "0");
						resultCode = "0";
						resultDesc = "成功";
						retMap.put("channel", channel);
						retMap.put("streamSeq", streamSeq);
					}
					// 匹配应急短信
				} else if (("1065716061102".equals(yjSendNumber)) || ("1065716061103".equals(yjSendNumber))) {
					// 判断应急短信开户，开户将字段置为1
					String ops = crmOpenInfo.getOps();
					String ecId = crmOpenInfo.getEcId();
					log.info("【CRM开户信息同步】应急短信判断操作类型：{}", ops);
					if ("1".equals(ops)) {
						// 开户
						String cityExtId = sendNumber.substring(14);
						log.info("【CRM开户信息同步】应急短信开户的地市编码：{}", cityExtId);
						int resultOpen = cRMMapper.yjOpenAccount(ecId, cityExtId);
						log.info("【CRM开户信息同步】应急短信开户：{}", resultOpen == 1 ? "成功" : "失败");
					} else if ("3".equals(ops)) {
						// 销户
						String cityExtId = sendNumber.substring(14);
						log.info("【CRM开户信息同步】应急短信销户的地市编码：{}", cityExtId);
						int resultOpen = cRMMapper.yjUpdataAccount(cityExtId);
						log.info("【CRM开户信息同步】应急短信销户：{}", resultOpen == 1 ? "成功" : "失败");
					}
				}
			
		} catch (Exception e) {
			// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultDesc = "CRM开户信息同步接口异常,error:" + e.getMessage();
			e.printStackTrace();
			log.info("调用CRM开户信息同步接口失败");
		}
		retMap.put("resultCode", resultCode);
		retMap.put("resultDesc", resultDesc);
		return retMap;
	}

	// 匹配精准政务
	public /* void */Map<String, Object> JZZW(String cRMOpenInfo) {
		JSONObject json = JSON.parseObject(cRMOpenInfo);
		String sendNumber = json.getString("sendNumber");
		JSONObject req = JSONObject.parseObject(cRMOpenInfo);
		String resp = "";
		Map<String, Object> retMapJ = new HashMap<String, Object>();
		try {
			log.info("精准政务开户信息同步接口入参(解压前)：{}", req);
			resp = this.httpPostWithJSON(jZZWUrl, req);
			// resp ="{\"resultCode\": \"0\", \"resultDesc\": \"成功\",
			// \"streamSeq\": \"20190809110306100001\"}" ;
			// 解压
			/*
			 * log.info("精准政务开户信息同步接口回参(解压前)：{}", resp); resp =
			 * GZipUtil.gunzip(resp); log.info("精准政务开户信息同步接口回参(解压后)：{}", resp);
			 */
			log.info("精准政务开户信息同步接口回参", resp);
			retMapJ = this.readJZZWResp(resp);
		} catch (Exception e) {
			e.printStackTrace();
			commonService.createSmsOperLog("6", "精准政务开户信息同步接口", "1", "精准政务开户接口");
			log.error("精准政务开户信息同步接口");
			throw new SmsException("精准政务开户信息同步接口异常");
		}
		return retMapJ;
	}

	public String httpPostWithJSON(String url, JSONObject jsonParam) throws Exception {
		DefaultHttpClient httpclient = null;
		HttpPost httpPost = null;
		HttpResponse response = null;
		org.apache.http.HttpEntity entity = null;
		String result = "";
		try {
			httpclient = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			StringEntity entityParam = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
			entityParam.setContentEncoding("UTF-8");
			entityParam.setContentType("application/json");
			httpPost.setEntity(entityParam);
			// 设置连接超时时间
			HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 20000);
			// 设置读数据超时时间
			HttpConnectionParams.setSoTimeout(httpclient.getParams(), 20000);
			response = httpclient.execute(httpPost);
			entity = response.getEntity();
			if (null != entity) {
				byte[] bytes = EntityUtils.toByteArray(entity);
				result = new String(bytes, "UTF-8");
			}
			return result;
		} catch (Exception e) {
			throw e;
		} finally {
			if (null != httpclient) {
				httpclient.getConnectionManager().shutdown();
			}
		}
	}

	private Map<String, Object> readJZZWResp(String resp) {
		String resultCode = "-1";
		String resultDesc = "失败";
		String streamSeq = "";
		Map<String, Object> retMap = new HashMap<String, Object>();
		if (resp != null && !"".equals(resp)) {
			JSONObject jsonObject = JSONObject.parseObject(resp);
			resultCode = jsonObject.getString("resultCode");
			resultDesc = jsonObject.getString("resultDesc");
			streamSeq = jsonObject.getString("streamSeq");
		}
		retMap.put("resultCode", resultCode);
		retMap.put("resultDesc", resultDesc);
		retMap.put("streamSeq", streamSeq);
		return retMap;
	}
}
